import { getUUid } from "@/focusSolid/path/until";
import { FocusContext } from "@/focusSolid/store/focus";
import { SwitchContext, getSwitchContext } from "@/focusSolid/store/switch";
import { onMount, onCleanup, useContext, createRenderEffect } from "solid-js";
import { TypePageFocus } from "../../type";
import { SolidFC } from "solid-shims";
import { KeyEvents } from "./keyMove";

const Index: SolidFC<{ keyBoardLock?: boolean, focusId?: string, popupKeyBoardLook?: boolean, onEnter?: () => void, onBack?: () => void }> = function (props) {
  const [focusState, { listenerKeyDown, unListenerKeyDown }] = useContext(FocusContext);
  const [switchState, switchOptions] = getSwitchContext()
  const uid = getUUid()
  const keyevent = new KeyEvents()
  function onSwitchKeyDown(key: keyof TypePageFocus.TypeKeys, keyEv: KeyboardEvent) {
    //判断当前组件是否被隐藏，如果被隐藏，则不监听按键
    if (props.keyBoardLock === true) return
    const _keyboard = focusState.keys
    //如果页面中有弹窗处于显示状态，并且指定弹窗显示状态也需要锁住键盘时，则不监听按键
    if (props.popupKeyBoardLook && focusState.popupList.find(v => v.visible)) return
    if (keyEv.keyCode === _keyboard.ENTER) props.onEnter && props.onEnter()
    if (keyEv.keyCode === _keyboard.BACK) props.onBack && props.onBack()
    console.time()
    keyevent.onKeyMove(keyEv, switchState, switchOptions, {
      keyboard: _keyboard,
      key,
    })
    console.timeEnd()
  }
  createRenderEffect(() => {
    if (typeof props.focusId === "string" && props.focusId) {
      switchOptions.changeFocus(props.focusId)
    }
  })
  onMount(() => {
    listenerKeyDown(uid, onSwitchKeyDown)
  })

  onCleanup(() => {
    unListenerKeyDown(uid)
  })
  return <SwitchContext.Provider value={[switchState, switchOptions]}>
    {props.children}
  </SwitchContext.Provider>
}

export default Index